package com.example.jetpacker.viewmodel

import android.content.Context
import android.content.SharedPreferences
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.common.base.AbsActivity
import com.example.jetpacker.R
import com.example.jetpacker.databinding.ActViewmodelOneBinding

/**
 * ViewModel
 * 存放Activity界面相关的数据、生命周期跟着Activity的销毁而销毁、屏幕旋转不会重建
 * implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
 */
@Route(path = "/jetpack/viewModel/one")
class ViewModelActivity : AbsActivity<ActViewmodelOneBinding>() {

    private lateinit var mViewModel: OneViewModel
    private lateinit var sp:SharedPreferences

    override fun getLayoutId()= R.layout.act_viewmodel_one

    override fun main() {
//        mViewModel = ViewModelProvider(this).get(OneViewModel::class.java)
        sp = getSharedPreferences("ApiTest", Context.MODE_PRIVATE)
        val countReserved = sp.getInt("count_reserved", 0)
        mViewModel = ViewModelProvider(this, ViewModelFactory(countReserved)).get(OneViewModel::class.java)
        refreshCounter()
    }

    override fun initListener() {
        mBinding.button.setOnClickListener{
            mViewModel.counter++
            refreshCounter()
        }

        mBinding.btnClear.setOnClickListener{
            mViewModel.counter = 0
            refreshCounter()
        }
    }

    private fun refreshCounter() {
        mBinding.tvText.text=mViewModel.counter.toString()
    }

    override fun onPause() {
        super.onPause()
        sp.edit().putInt("count_reserved",mViewModel.counter).apply()
    }
}